import subprocess
import logging
import os
from dingtalkchatbot.chatbot import DingtalkChatbot

LOG_PATH='/........./alert_.......log'
LOG_SEEK_PATH='alter_seek.pos'
LOG_TMP_PATH='/tmp/alter.log.tmp'
MSG_HEAD = 'oracle日志:\n'
SPLIT_STR='----------'
HOSTNAME="....."
PROJECT="....."
WEBHOOK = 'https://oapi.dingtalk.com/robot/send?access_token=......'
SECRET = '......'
logging.basicConfig(
    filename="info.log",
    format="%(asctime)s-%(name)s-%(levelname)s %(message)s",
    level=logging.DEBUG)


def exec_command(shell):
    logging.info("exec shell: {0}".format(shell))
    result = subprocess.Popen(
        shell, stdin=subprocess.PIPE, stderr=subprocess.PIPE,
        stdout=subprocess.PIPE, universal_newlines=True, shell=True, bufsize=1)
    stdout_list = result.stdout.readlines()
    stderr_list = result.stderr.readlines()
    _, _ = result.communicate()
    returncode = result.returncode
    if returncode != 0:
        logging.error("rxec shell eturncode: {0}".format(returncode))
        for stderr in stderr_list:
            logging.error(stderr)
        exit(1)
    logging.info("exec shell returncode: {0}".format(returncode))
    logging.info("exec shell is success")
    return stdout_list


def dingding_send(msg):
    logging.info("msg sed {0}".format(WEBHOOK))
    xiaoding = DingtalkChatbot(WEBHOOK, secret=SECRET)
    xiaoding.send_text(msg=msg)

if __name__ == '__main__':
    log_seek = ''
    if os.path.exists(LOG_SEEK_PATH):
        with open(LOG_SEEK_PATH,'r') as log_seek_obj:
            log_seek = log_seek_obj.read()
    if not log_seek.isdigit():
        log_seek = 0
    else:
        log_seek=int(log_seek)
    with open(LOG_PATH,'r', encoding="GBK") as log_obj:
        log_obj.seek(0,2)
        if log_seek > log_obj.tell():
            log_seek = 0
        log_obj.seek(log_seek,0)
        log_msg=str(log_obj.read())
        log_seek=log_obj.tell()
    with open(LOG_TMP_PATH,'w') as log_tmp_obj:
        log_tmp_obj.write(log_msg)
    with open(LOG_SEEK_PATH,'w') as log_seek_obj:
        log_seek_obj.write(str(log_seek))
    awk_shell = """
                awk 'BEGIN{log_line=0}
                {status=$0 ~/^[A-Z].* [0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2} [0-9]{4}$/;
                if( status == 1 ){log_line++};
                l[log_line]=l[log_line]"\\n"$0;}
                END{for(i=1;i<=length(l);i++){status=l[i] ~/(ORA-|TNS-|WARNING)/;
                if( status == 1 ){print l[i];print \"""" \
                + SPLIT_STR + "\"}}}' " \
                + LOG_TMP_PATH + " && > " + LOG_TMP_PATH

    awk_stdout_list = exec_command(awk_shell)
    awk_msgs_list = ''.join(awk_stdout_list).split(SPLIT_STR)
    for awk_msgs in awk_msgs_list[-10:-1]:
        awk_msgs = "....\n" \
                   "项目:{}\n" \
                   "主机:{}\n" \
                   "日志路径:\n{}\n" \
                   "报错内容:\n{}".format(PROJECT,HOSTNAME,LOG_PATH,awk_msgs)
        dingding_send(awk_msgs)